﻿using AutoMapper;
using Consul;
using InventoryIssue.API.Write.Application.Command.Allocate;
using InventoryIssue.Domain;
using InventoryIssue.ErrorCode;
using InventoryIssue.Infrastructrue.Implement;
using MediatR;
using SqlSugar.SplitTableExtensions;

namespace InventoryIssue.API.Write.Application.Handler.Allocate
{
    /// <summary>
    /// 创建调拨单处理器
    /// 负责处理库存调拨单的创建逻辑，包括主单和产品明细的插入
    /// </summary>
    public class CreateAllocateHandler : IRequestHandler<CreateAllocateCommand, APIResult<int>>
    {
        /// <summary>
        /// 数据库上下文，用于数据库操作
        /// </summary>
        private readonly DatabaseContext db;
        
        /// <summary>
        /// AutoMapper映射器，用于对象转换
        /// </summary>
        private readonly IMapper mapper;

        /// <summary>
        /// 构造函数，注入依赖项
        /// </summary>
        /// <param name="db">数据库上下文</param>
        /// <param name="mapper">对象映射器</param>
        public CreateAllocateHandler(DatabaseContext db, IMapper mapper)
        {
            this.db = db;
            this.mapper = mapper;
        }
        /// <summary>
        /// 处理创建调拨单命令
        /// </summary>
        /// <param name="request">创建调拨单命令对象</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>返回API结果，包含插入的产品数量</returns>
        public async Task<APIResult<int>> Handle(CreateAllocateCommand request, CancellationToken cancellationToken)
        {
            try
            {
                // 初始化返回结果
                APIResult<int> result = new APIResult<int>();

                // 验证产品列表不能为空
                if (request.Products == null || !request.Products.Any())
                {
                    result.Message = "产品列表不能为空";
                    result.Code = APIEnum.Fail;
                    return result;
                }
                
                // 验证产品是否存在
                var productIds = request.Products.Select(p => p.ProductId).ToList();
                var existingProducts = await db.SqlSugar.Queryable<BasicInformation.Domain.ProductModel>()
                    .Where(p => productIds.Contains(p.ProductId))
                    .Select(p => new { p.ProductId, p.ProductCode })
                    .ToListAsync();

                if (existingProducts.Count != productIds.Count)
                {
                    result.Message = "部分产品不存在，请检查产品ID";
                    result.Code = APIEnum.Fail;
                    return result;
                }

                // 开始数据库事务
                await db.SqlSugar.Ado.BeginTranAsync();

                // 手动创建调拨单主表模型，确保所有字段都被正确设置
                var mainModel = new AllocateModel
                {
                    AllocateId = request.AllocateId,
                    OrderNumber = request.OrderNumber,
                    AllocateWarehouseIn = request.AllocateWarehouseIn,
                    AllocateWarehouseOut = request.AllocateWarehouseOut,
                    Note = request.Note,
                    OrderCreator = request.OrderCreator,
                    OrderCreatorTime = request.OrderCreatorTime,
                    Manager =null,
                    ManagerTime =null,
                    State = request.State,
                    IsDel = false
                };

                await db.SqlSugar.Insertable(mainModel).ExecuteCommandAsync();

                // 构建调拨产品明细列表
                var allocateProductModels = request.Products
                    .Select(code => new AllocateProductModel
                    {
                        AllocateId = request.AllocateId,    // 调拨单ID
                        ProductId = code.ProductId,         // 产品ID
                        Quantity = code.Quantity,           // 调拨数量
                        CreateTime = DateTime.Now,          // 创建时间
                    })
                    .ToList();

                // 批量插入调拨产品明细
                var insertCount = await db.SqlSugar
                    .Insertable(allocateProductModels)
                    .ExecuteCommandAsync();

                //增加操作记录
                OperationLog log = new OperationLog()
                {
                    Operator = request.OrderCreator,
                    AllocateId = request.AllocateId,
                    OperationType = "新增",
                    OperationContent = request.Note,
                    CreateTime=DateTime.Now,
                    IsDel=false
                };
                await db.SqlSugar.Insertable(log).ExecuteReturnIdentityAsync();

                // 提交事务
                await db.SqlSugar.Ado.CommitTranAsync();

                // 设置成功返回结果
                result.Message = $"成功创建调拨单并关联 {insertCount} 个产品";
                result.Code = APIEnum.Ok;
                result.Data = insertCount;
                return result;
            }
            catch (Exception ee)
            {
                // 发生异常时回滚事务
                await db.SqlSugar.Ado.RollbackTranAsync();
                
                // 重新抛出异常，让上层处理
                throw;
            }
        }
    }
}
